package com.itzhanshen.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 使用@PreAuthorize开启注解全局方法默认
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 配置密码加密器
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
    // 设置那些用户可以访问该系统
    //@Bean
 /*   @Override
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        *//*inMemoryUserDetailsManager.createUser(User.withUsername("itzhanshen").password("{noop}123456").authorities("ROLE_ADMIN","p1").build());
        inMemoryUserDetailsManager.createUser(User.withUsername("zhanshen").password("{noop}123456").authorities("ROLE_ADMIN", "p2").build());
        *//*
        // 利用 密码加密器生成
        inMemoryUserDetailsManager.createUser(User.withUsername("itzhanshen").password(bCryptPasswordEncoder().encode("123456")).authorities("ROLE_ADMIN","p1").build());
        inMemoryUserDetailsManager.createUser(User.withUsername("zhanshen").password(bCryptPasswordEncoder().encode("123456")).authorities("ROLE_ADMIN", "p2").build());
        return inMemoryUserDetailsManager;
    }  */
    // 从数据库查询用户信息及用户密码
/*    @Bean
    @Override
    protected UserDetailsService userDetailsService() {
        return new JdbcUserDetailsManager();
    }*/
 // 指定访问资源的权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().and().logout().and().csrf().disable()
                .authorizeRequests()
                //.antMatchers("/hello").permitAll() //不登录也能访问
                //.antMatchers("/say").hasRole("ADMIN") // 用户为admin才能访问
                //.antMatchers("/register").hasAnyAuthority("p1") //权限为p1的才能访问
                .anyRequest().authenticated(); //其他的只要登录就能访问
    }

}
